package com.veterinaria.dao;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.veterinaria.bean.CreditoBean;
import com.veterinaria.bean.EmpleadoBean;
import com.veterinaria.services.CreditoService;

public class CreditoDAO implements CreditoService{
	
	SqlSessionFactory sqlmapper= null;{
		try {	
	   	 	Reader reader = Resources.getResourceAsReader("ConfiguracionIbatis.xml");
	   	 	sqlmapper =new  SqlSessionFactoryBuilder().build(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void grabarCredito(CreditoBean obj) throws Exception {
		SqlSession session = sqlmapper.openSession();
		try {
			session.insert("creditoxml.grabarCredito",obj);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}finally{ session.close();}
	}

	@Override
	public CreditoBean obtenerCredito(CreditoBean cre) throws Exception {
		
		CreditoBean cred=null;
		SqlSession session = sqlmapper.openSession();			
		try {				
			cred= (CreditoBean) session.selectOne("creditoxml.obtenerCredito",cre);				
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ session.close();}
		return cred;
	}

	@Override
	public Integer codCredito() throws Exception {
		Integer cred=null;
		SqlSession session = sqlmapper.openSession();			
		try {				
			cred= (Integer) session.selectOne("creditoxml.codMaxCredito");				
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ session.close();}
		return cred;
	}

	@Override
	public void actualizarCredito(CreditoBean cre) throws Exception {
		
		SqlSession session = sqlmapper.openSession();
		String msg="";
		try {
			msg="exito"+ session.insert("creditoxml.actualizarCredito",cre);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			msg=e.getMessage();
			session.rollback();
		}finally{ session.close();}
		
	}

}
